"use client";

import { Icon } from "@/components/Icon";
import { Poster } from "@/components/Poster";
import { TypeWriter } from "@/components/TypeWriter";
import MoveDown from "@/components/MoveDown";
import {
  Lanyard,
  Folder,
  Carousel,
  Stack,
  TiltedCard,
} from "@/components/Animation";
import Link from "next/link";
import AboutBox from "@/components/AboutBox";
import { useIsMobile } from "@/hooks/use-mobile";
import { gameList } from "@/config/game";
import classNames from "classnames";
import { useSizeScale } from "@/hooks/use-size-scale";
import Danmaku from "rc-danmaku";
import { useEffect, useRef } from "react";

function Content() {
  return (
    <div className="h-screen w-full relative mb-[5vh] md:mb-[15vh]">
      {/* <Poster /> */}
      {/* <div className="opacity-0 content-animation flex items-center justify-center w-full h-screen"> */}
      <div className="flex items-center justify-center w-full h-screen">
        <div className="w-fit h-fit flex flex-col gap-y-6 px-6">
          <p className=" text-2xl tracking-widest  md:text-5xl">Hello，我是</p>
          <strong
            className="text-5xl md:text-8xl tracking-widest font-black bg-clip-text bg-gradient-to-r from-cyan-400 to-blue-500"
            style={{
              WebkitTextFillColor: "transparent",
            }}
          >
            展程
          </strong>
          <p className="text-2xl md:text-5xl tracking-widest">
            喜欢
            <span className="font-semibold text-[#e98fe8]">唱</span>、
            <span className="font-semibold text-[#42B883]">跳</span>、
            <span className="font-semibold text-[#007acc]">rap</span>、
            <span className="font-semibold text-[#e69213]">篮球</span>
          </p>
          <div>
            <TypeWriter />
          </div>

          <div className="text-xl md:text-3xl tracking-widest flex items-center">
            <span>吃饭的工具：</span>
            <div className="flex items-center gap-x-5">
              <Icon name="react" />
              <Icon name="Vue" />
              <Icon name="typescript" />
              <Icon name="electron" />
              <Icon name="Nodejs" />
            </div>
          </div>
        </div>
        <MoveDown />
      </div>
    </div>
  );
}

function About() {
  const isMobile = useIsMobile();
  const danmakuContainerRef = useRef<HTMLDivElement>(null);
  const danmakuInsRef = useRef<Danmaku | null>(null);

  // 弹幕文本池
  const danmakuTexts = [
    "Hello, world!",
    "欢迎来到我的世界 🎉",
    "React 真好玩！",
    "Vue 也不错哦~",
    "TypeScript 是神！",
    "前端开发者加油！💪",
    "代码改变世界",
    "学无止境 📚",
    "保持热爱，奔赴山海",
    "今天也要努力呀！",
    "做最好的自己 ✨",
    "梦想还是要有的",
    "代码写得真漂亮",
    "技术改变生活",
    "永远相信美好的事情即将发生",
    "加油！奥利给！",
    "你好呀 👋",
    "很高兴认识你",
    "一起学习进步吧",
    "Keep coding, keep growing",
  ];

  // 生成随机颜色
  const getRandomColor = () => {
    const colors = [
      "#FF6B6B", // 红色
      "#4ECDC4", // 青色
      "#45B7D1", // 蓝色
      "#FFA07A", // 橙色
      "#98D8C8", // 薄荷绿
      "#F7DC6F", // 黄色
      "#BB8FCE", // 紫色
      "#85C1E2", // 天蓝
      "#F8B500", // 金色
      "#FF85A2", // 粉色
      "#7DCEA0", // 绿色
      "#F06292", // 玫红
      "#AED581", // 浅绿
      "#FFD54F", // 亮黄
      "#90CAF9", // 浅蓝
    ];
    return colors[Math.floor(Math.random() * colors.length)];
  };

  // 获取随机弹幕文本
  const getRandomText = () => {
    return danmakuTexts[Math.floor(Math.random() * danmakuTexts.length)];
  };

  // 初始化弹幕
  useEffect(() => {
    if (danmakuContainerRef.current) {
      const danmaku = new Danmaku(danmakuContainerRef.current, {
        rowHeight: 80, // 弹幕轨道高度
        speed: 100, // 弹幕速度（降低一点，让它们飘得慢一些）
        opacity: 1, // 不透明度
        minGapWidth: 60, // 弹幕之间的最小间隔（减小间隔，让弹幕能更快填充轨道）
      });
      danmakuInsRef.current = danmaku;

      // return () => {
      //   // 组件卸载时销毁弹幕实例
      //   if (danmakuInsRef.current) {
      //     danmakuInsRef.current.destroy();
      //   }
      // };
    }
  }, []);

  // 定时发送弹幕 - 让每条弹幕独立、随机地出现
  useEffect(() => {
    if (!danmakuInsRef.current) return;

    const timeoutIds: NodeJS.Timeout[] = [];
    let isActive = true;

    const sendSingleDanmaku = () => {
      if (danmakuInsRef.current && isActive) {
        // 每次只发送 1 条弹幕
        danmakuInsRef.current.push(getRandomText(), {
          color: getRandomColor(),
        });
      }
    };

    // 创建多个独立的弹幕发送流，让上下轨道都能被使用
    const createDanmakuStream = (initialDelay: number) => {
      const scheduleNext = () => {
        if (!isActive) return;

        // 随机间隔 600ms - 1500ms
        const randomDelay = Math.random() * 900 + 600;

        const timeoutId = setTimeout(() => {
          sendSingleDanmaku();
          scheduleNext();
        }, randomDelay);

        timeoutIds.push(timeoutId);
      };

      // 初始延迟后开始
      const timeoutId = setTimeout(() => {
        sendSingleDanmaku();
        scheduleNext();
      }, initialDelay);

      timeoutIds.push(timeoutId);
    };

    // 创建 3-4 个独立的弹幕流，错开时间开始
    createDanmakuStream(0);
    createDanmakuStream(600);

    // 清理函数
    return () => {
      isActive = false;
      timeoutIds.forEach((id) => clearTimeout(id));
    };
  }, []);

  return (
    <div className="min-h-screen w-full flex items-center justify-center relative">
      <div className="w-screen h-[200vh] absolute z-20">
        <Lanyard position={[0, 0, 20]} />
      </div>

      <div
        ref={danmakuContainerRef}
        className="h-screen w-full flex items-center justify-center absolute inset-0 z-10"
      />
    </div>
  );
}

function Experience() {
  const isMobile = useIsMobile();
  const scale = useSizeScale(1440, {
    min: 768,
    max: 1440,
  });
  const contactMeList = [
    {
      name: "Github",
      link: "https://github.com/zhengyuxiang",
      icon: "github",
    },
    {
      name: "微信",
      link: "https://github.com/zhengyuxiang",
      icon: "wx",
    },
    {
      name: "qq",
      link: "https://github.com/zhengyuxiang",
      icon: "qq",
    },
    {
      name: "邮件",
      link: "https://github.com/zhengyuxiang",
      icon: "email",
    },
    {
      name: "知乎",
      link: "https://github.com/zhengyuxiang",
      icon: "zhihu",
    },
    {
      name: "b站",
      link: "https://github.com/zhengyuxiang",
      icon: "bilibili",
    },
  ];

  const AboutBoxList = [
    {
      leftNode: (
        <>
          <div className="text-4xl font-bold tracking-widest mb-8">
            主要技术栈
          </div>
          <div className="text-xl flex flex-col gap-4">
            <span>
              <span className="text-blue-400">React</span>、
              <span className="text-green-600">Vue</span>
            </span>
            <span>
              <span>javascript</span>、<span>typescript</span>
            </span>
            <span>
              <span>css、gsap</span>
            </span>
          </div>

          <div className="text-2xl font-light tracking-widest mt-8">
            以前喜欢逻辑，现在喜欢交互
          </div>
        </>
      ),
      rightNode: (
        <div className="mt-20">
          <TiltedCard
            imageWidth={isMobile ? 200 : 300 * scale}
            imageHeight={isMobile ? 200 : 300 * scale}
            imageSrc="/img/fe.jpg"
            captionText="React Vue TS JS Node Electron"
            showTooltip
            displayOverlayContent
            overlayContent={
              <div className="text-white px-8 md:px-12 py-8">
                <div className="flex items-center gap-x-2 md:gap-x-5 text-2xl">
                  <Icon name="react" />
                  <Icon name="Vue" />
                  <Icon name="typescript" />
                  <Icon name="electron" />
                  <Icon name="Nodejs" />
                </div>
              </div>
            }
          />
        </div>
      ),
    },
    {
      leftNode: (
        <>
          <div className="text-4xl font-bold tracking-widest mb-8">
            一些奇怪的项目
          </div>
          <div className="text-xl flex flex-col gap-4">
            <span>cc-designer</span>
            <span>cloud-designer</span>
            <span>还有你所看到的博客</span>
          </div>

          <div className="text-2xl font-light tracking-widest mt-8">
            喜欢做一些奇奇怪怪的项目☺
          </div>
        </>
      ),
      rightNode: (
        <div className={classNames(!isMobile ? "mt-40 ml-30" : "mt-35")}>
          {/* <Carousel baseWidth={400 * scale} /> */}
          <Folder
            size={isMobile ? 1.5 : 3 * scale}
            color="#51a2ff"
            items={[
              <div
                className="w-full h-full rounded-[10px]"
                style={{
                  backgroundImage: `url(/img/project/cc-designer.png)`,
                  backgroundSize: "cover",
                  backgroundPosition: "center",
                  backgroundRepeat: "no-repeat",
                }}
              />,
              <div
                className="w-full h-full rounded-[10px]"
                style={{
                  backgroundImage: `url(/img/project/cloud-designer.png)`,
                  backgroundSize: "cover",
                  backgroundPosition: "center",
                  backgroundRepeat: "no-repeat",
                }}
              />,
              <div
                className="w-full h-full rounded-[10px]"
                style={{
                  backgroundImage: `url(/img/project/cgx-component.png)`,
                  backgroundSize: "cover",
                  backgroundPosition: "center",
                  backgroundRepeat: "no-repeat",
                }}
              />,
            ]}
          />
        </div>
      ),
    },
    {
      leftNode: (
        <>
          <div className="text-4xl font-bold tracking-widest mb-8">
            主要训练的游戏
          </div>
          <div className="text-xl flex flex-col gap-4">
            <span>CS2</span>
            <span>王者荣耀</span>
            <span>英雄联盟-云顶之弈</span>
            <span>......</span>
          </div>

          <div className="text-2xl font-light tracking-widest mt-8">
            竞速、FPS、格斗以及MOBA都有涉猎
          </div>
        </>
      ),
      rightNode: (
        <div className="mt-20">
          <Stack
            cardsData={gameList.slice(12).map((gameItem, index) => {
              return { id: index, img: gameItem.img };
            })}
            cardDimensions={{
              width: isMobile ? 200 : 250 * scale,
              height: isMobile ? 250 : 350 * scale,
            }}
          />
        </div>
      ),
    },
  ];
  return (
    <div className="min-h-screen w-full relative z-[40]">
      <div className="w-full flex flex-col items-center mt-[5vh] md:mt-[15vh]">
        {AboutBoxList.map((item, index) => (
          <AboutBox
            key={index}
            index={index + 1}
            leftNode={item.leftNode}
            rightNode={item.rightNode}
            className={classNames(
              !isMobile && index === 0 && "translate-x-[20%]",
              !isMobile && index === 1 && "translate-x-[-20%]"
            )}
          />
        ))}
      </div>
    </div>
  );
}

export default function Home() {
  return (
    <div className="relative h-fit w-full overflow-x-hidden">
      {/* 正文内容 - 初始隐藏，在所有动画完成后淡入显示 */}
      <Content />
      {/* 关于我 */}
      <About />
      {/* 经历内容 */}
      <Experience />
    </div>
  );
}
